<template>
    <div>
        <div class="search">
            <van-search v-model="message" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" />
        </div>
        <div class="history">
            <ul>
                <li v-for="(value,index) in store.searchHistory" :key="index"
                @click="onClick(value)">
                    <span>{{ value }}</span>
                </li>
            </ul>
            <van-button type="primary" size="mini" @click="fn">清空</van-button>
        </div>
        <div class="main">
            <ul>
                <li v-for="value in list" :key="value.food_id" @click="sp(value.food_id)">
                    <img :src="getImg(value.pic)" alt="">
                    <h2>食品：{{ value.foodname }}</h2>
                </li>
            </ul>
        </div>
    </div>
</template>

<script setup>
import { ref,onMounted,reactive } from 'vue';
import { getFoodBySearchApi } from '@/api';
import { useRoute,useRouter } from 'vue-router'; 
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore();
const getImg = e => `http://172.17.18.240:8080/nfood${e}`;
const route =useRoute();
const router =useRouter();
const list =ref([]);
const message =ref('');
const onSearch = () => {
    getFoodBySearch(message.value);
    console.log("mass"+message.value);
    if(store.searchHistory.indexOf(message.value)===-1){
        store.searchHistory.unshift(message.value);
    }else{
        store.searchHistory.splice(store.searchHistory.indexOf(message.value),1);
        store.searchHistory.unshift(message.value);
    }
  };
  const onClear = () => {
    if(message.value===''){
        return
    }if(message.value!==''){
        list.value.spline(0)
    }
  };
  const fn = () => {
    store.clearSearch();
  };
  const onClick = (e) => {
    if(list.value.length===0){
        getFoodBySearch(e);
    }
    if(list.value.length>0){
        getFoodBySearch(e);
    }
    message.value = e;
    getFoodBySearch(e);
  };
const onCancel = () => {
    router.push('/');
    message.value = '';
  };
  const sp = e => {
    router.push({
      path:'/detail',
      query:{
        foodId:e
      }
    });
  };
const getFoodBySearch = async e => {
    const res = await getFoodBySearchApi(e);
    list.value=res;
  };
</script>

<style scoped>
.history ul{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.history ul>span{
    width: 20%;
}
.history ul>li{
    width: 15%;
    margin-right: 5px;
    text-align: left;
}
.main ul{
width: 100%;
}
.main>ul li{
    margin: 10px;
    width: 100%;
    display: flex;
    align-items: center;
}
.main>ul>li img{
    border-radius: 10px;
    margin: 0 10px;
     width: 50px;
     height: 50px;
}
</style>